<script>
import Number from "../components/number.vue"
import { getPackageTypes, getUnloadTypes, submitGoodsInfo } from '@/api/publish'
import GoodsType from "../enum/GoodsType"
export default {
	components: {
		Number
	},
	data() {
		return {
			GoodsType,
			showNameModal: true,
			historyNames: [
				this.$t('办公用品'),
				this.$t('电子产品'),
				this.$t('生活用品'),
				this.$t('服装鞋帽'),
				this.$t('食品'),
				this.$t('建材'),
				this.$t('机械设备')
			],
			formData: {
				goods_h: "", // 高
				goods_l: "", // 长
				goods_num: "", // 数量
				goods_volume: "", // 体积
				goods_w: "", // 宽
				goods_weight: "", // 重量
				image: "", // 图片
				package_id: "", // 包装id
				package_name: "", // 包装名称
				title: "", // 货物名称
				unload_id: "", // 卸货id
				user_id: uni.getStorageSync('user_id')
			},
			fileList1: [],
			// 包装方式选项，初始为空数组
			packageTypes: [],
			// 装卸方式选项，初始为空数组
			unloadTypes: [],
			// 特殊尺寸组
			sizeGroups: [{
				length: '', // 长
				width: '',  // 宽
				height: '', // 高
			}],
			// 最大尺寸组数量
			maxSizeGroups: 5,
			// 添加临时存储的货物名称
			tempGoodsName: '',
			showNameModal: false
		}
	},
	// 页面加载时获取数据
	async created() {
		await Promise.all([
			this.getPackageTypeList(),
			this.getUnloadTypeList()
		])
	},
	methods: {
		back() {
			// uni.navigateBack()
			this.cback()
		},
		clickTabs(index) {
			this.tabIndex = index
		},
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList${event.name}`][fileListLen]
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: 'https://app.gluz.com.cn/api/common/upload',
					filePath: url,
					name: 'file',
					success: (res) => {
						const data = JSON.parse(res.data)
						resolve(data.data.fullurl)
					}
				});
			})
		},
		async submit() {
			// 表单验证
			if (!this.formData.title) {
				return uni.showToast({
					title: this.$t('请输入货物名称'),
					icon: 'none'
				})
			}
			if (!this.formData.package_id && !this.formData.package_name) {
				return uni.showToast({
					title: this.$t('请选择或填写包装方式'),
					icon: 'none'
				})
			}
			if (!this.formData.goods_weight) {
				return uni.showToast({
					title: this.$t('请输入货物重量'),
					icon: 'none'
				})
			}
			if (!this.formData.goods_volume) {
				return uni.showToast({
					title: this.$t('请输入货物体积'),
					icon: 'none'
				})
			}
			if (!this.formData.goods_num) {
				return uni.showToast({
					title: this.$t('请输入包装总件数'),
					icon: 'none'
				})
			}

			// 特殊尺寸验证
			const hasIncompleteSizes = this.sizeGroups.some(group => {
				const { length, width, height } = group
				return (length || width || height) && !(length && width && height)
			})

			if (hasIncompleteSizes) {
				return uni.showToast({
					title: this.$t('请完整填写货物尺寸'),
					icon: 'none'
				})
			}

			// 处理尺寸数据
			this.formatSizeGroups()

			// 图片验证
			if (this.fileList1.length === 0) {
				return uni.showToast({
					title: this.$t('请上传货物照片'),
					icon: 'none'
				})
			}

			// 更新图片数据到formData
			this.formData.image = this.fileList1.map(item => item.url).join(',')

			try {
				uni.showLoading({
					title: this.$t('提交中'),
					mask: true
				})

				const res = await submitGoodsInfo(this.formData)

				if (res.data.code === 200) {
					uni.showToast({
						title: this.$t('提交成功'),
						icon: 'success'
					})
					this.$store.state.publishCommonBody.goods_id = res.data.data.data.id
					this.$emit('confirm', Object.assign(this.formData, res.data.data.data))
				} else {
					uni.showToast({
						title: res.data.msg || this.$t('提交失败'),
						icon: 'none'
					})
				}
			} catch (e) {
				console.log(e);
				uni.showToast({
					title: '提交失败1',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		// 选择装卸方式
		selectUnloadType(id) {
			this.formData.unload_id = id === this.formData.unload_id ? "" : id
		},
		selectPackageType(id) {
			this.formData.package_id = id === this.formData.package_id ? "" : id
			if (id == this.formData.package_id) {
				this.formData.package_name = ""
			} else {
				this.formData.package_name = this.packageTypes.find(item => item.id == id).title
			}
		},
		// 计算货物密度
		getDensity() {
			if (this.formData.goods_weight && this.formData.goods_volume) {
				return (this.formData.goods_weight * (this.$store.state.publishCommonBody.goods_type == GoodsType.DAJIAN ? 1000 : 1) / this.formData.goods_volume).toFixed(2)
			}
			return 0
		},

		// 添加尺寸组
		addSizeGroup() {
			if (this.sizeGroups.length >= this.maxSizeGroups) {
				return uni.showToast({
					title: `最多{{$t('添加')}}${this.maxSizeGroups}组尺寸`,
					icon: 'none'
				})
			}

			this.sizeGroups.push({
				length: '',
				width: '',
				height: ''
			})
		},

		// {{$t('删除')}}{{$t('尺寸')}}组
		removeSizeGroup(index) {
			if (this.sizeGroups.length <= 1) {
				return uni.showToast({
					title: this.$t('至少保留一组尺寸'),
					icon: 'none'
				})
			}

			this.sizeGroups.splice(index, 1)
		},

		// 提交时处理尺寸数据
		formatSizeGroups() {
			// 过滤掉空的尺寸组
			const validGroups = this.sizeGroups.filter(group =>
				group.length && group.width && group.height
			)

			if (validGroups.length > 0) {
				// 更新到 formData
				this.formData.goods_l = validGroups.map(g => g.length).join(',')
				this.formData.goods_w = validGroups.map(g => g.width).join(',')
				this.formData.goods_h = validGroups.map(g => g.height).join(',')
			} else {
				// 清空尺寸数据
				this.formData.goods_l = ''
				this.formData.goods_w = ''
				this.formData.goods_h = ''
			}
		},

		// 获取包装方式列表
		async getPackageTypeList() {
			try {
				const res = await getPackageTypes()
				if (res.data.code === 200) {
					//找到数据中的其他并且删除
					const plusIndex = res.data.data.data.findIndex(item => item.id === 0)
					res.data.data.data.splice(plusIndex, 1)
					// {{$t('添加')}}$t('其他')选项
					this.packageTypes = [
						...res.data.data.data,
						{ id: 0, title: this.$t('其他') }
					]
				} else {
					uni.showToast({
						title: res.data.msg || this.$t('获取包装方式失败'),
						icon: 'none'
					})
				}
			} catch (e) {
				uni.showToast({
					title: this.$t('获取包装方式失败'),
					icon: 'none'
				})
			}
		},

		// 打开{{$t('货物名称')}}模态窗
		openNameModal() {
			this.tempGoodsName = this.formData.title // 初始化临时名称
			this.showNameModal = true
		},

		// {{$t('选择')}}{{$t('历史记录')}}
		selectHistory(name) {
			this.tempGoodsName = name
		},

		// {{$t('确认')}}{{$t('货物名称')}}
		confirmName() {
			if (!this.tempGoodsName) {
				return uni.showToast({
					title: this.$t('请输入货物名称'),
					icon: 'none'
				})
			}
			this.formData.title = this.tempGoodsName
			this.showNameModal = false
		},

		// {{$t('清空')}}{{$t('历史记录')}}
		clearHistory() {
			this.historyNames = []
			uni.showToast({
				title: this.$t('已清空历史记录'),
				icon: 'none'
			})
		},

		// 获取{{$t('装卸方式')}}{{$t('列表')}}
		async getUnloadTypeList() {
			try {
				const res = await getUnloadTypes()
				if (res.data.code === 200) {
					this.unloadTypes = res.data.data.data
				} else {
					uni.showToast({
						title: res.data.msg || this.$t('获取装卸方式失败'),
						icon: 'none'
					})
				}
			} catch (e) {
				uni.showToast({
					title: this.$t('获取装卸方式失败'),
					icon: 'none'
				})
			}
		},

		// 测试{{$t('数据')}}填充函数
		fillTestData() {
			// 填充基础信息
			this.formData = {
				title: this.$t('测试货物'),
				package_id: 1, // 纸箱装
				package_name: '',
				unload_id: 1, // 叉车
				goods_weight: 2.5, // 2.5吨
				goods_volume: 3, // 3立方米
				goods_num: 100, // 100件
				goods_l: '2.5,3.0', // 多组尺寸用逗号分隔
				goods_w: '1.8,2.0',
				goods_h: '1.5,1.8',
				image: 'https://example.com/test.jpg', // 测试图片地址
				user_id: uni.getStorageSync('user_id')
			}

			// 填充{{$t('尺寸')}}组{{$t('数据')}}
			this.sizeGroups = [
				{
					length: '2.5',
					width: '1.8',
					height: '1.5'
				},
				{
					length: '3.0',
					width: '2.0',
					height: '1.8'
				}
			]

			// 模拟{{$t('图片')}}{{$t('列表')}}
			this.fileList1 = [{
				url: 'https://example.com/test.jpg',
				status: 'success',
				message: ''
			}]

			// {{$t('关闭')}}{{$t('货物名称')}}弹窗
			this.showNameModal = false

			uni.showToast({
				title: this.$t('测试数据已填充'),
				icon: 'success'
			})
		}
	}
}
</script>
<template>
	<view class="h-full flex flex-col between overflow-hidden" style="align-items: stretch;">
		<!-- <pre>
			{{ formData }}
		</pre> -->
		<!-- <view class="tabs_nav">
			<view class="item" :class="tabIndex == 0 ? 'hover' : ''" @click="clickTabs(0)">
				<u-icon name="map" :color="tabIndex == 0 ? '#278AFF' : '#333'" size="36rpx"></u-icon>
				<view class="name">
					{{$t('自主发货')}}
				</view>
			</view>
			<view class="item" :class="tabIndex == 1 ? 'hover' : ''" @click="clickTabs(1)">
				<u-icon name="file-text" :color="tabIndex == 1 ? '#278AFF' : '#333'" size="36rpx"></u-icon>
				<view class="name">
					{{$t('订单发货')}}
				</view>
			</view>
		</view> -->
		<!-- 
		<view class="guanl_order">
			<view class="name">
				{{$t('关联订单')}}
			</view>
			<view class="info">
				<navigator url="#" hover-class="none">
					GL0455456772324
				</navigator>
				<u-icon name="arrow-right" color="#8C8C8C" size="28rpx"></u-icon>
			</view>
		</view> -->
		<!-- <div style="height: 50rpx;background:#fff;"></div>
		<div class="header">
			<div class="back center" @click="back">
				<image src="/static/icon/back.png" mode="widthFix" class="w-20"></image>
			</div>
			{{$t('货物信息')}}
		</div> -->

		<div class="overflow-auto" style="overflow: auto;flex:1">
			<u-popup :show="showNameModal" mode="bottom" :closeable="true" @close="showNameModal = false">
				<view class="name-modal">
					<view class="goods_info_title">
						<div class="between w-full">
							<div class="flex">
								<view class="name">
									{{$t('货物名称')}}
								</view>
								<view class="tag">
									{{$t('必填')}}
								</view>
							</div>
							<view class="text-gray-900 fz22 ml-20 " style="font-weight: initial;">
								{{ tempGoodsName.length }}/50
							</view>
						</div>
					</view>
					<view class="btn pl-20 pr-20 mb-20">
						<u-input style="background: #f5f5f5;" v-model="tempGoodsName" maxlength="50"
							:placeholder="$t('请输入货物名称')" />
					</view>
					<view class="history-header">
						<view class="history-title">{{$t('历史记录')}}</view>
						<view class="clear-btn flex" @click="clearHistory">
							<image src="/static/icon/delall.png" class="w-30 mr-10" mode="widthFix"></image>
							{{$t('清空')}}
						</view>
					</view>
					<view class="history-list">
						<view class="history-item" v-for="(item, index) in historyNames" :key="index"
							@click="selectHistory(item)">
							{{ item }}
						</view>
					</view>
					<view class="bg-primary text-center text-white py-20 rounded-50 ml-20 mr-20 mt-50"
						@click="confirmName">
						{{$t('确认')}}</view>
				</view>
			</u-popup>
			<view class="bor_bgff">
				<view class="goods_info_title">
					<view class="name">
						{{$t('货物名称')}}
					</view>
					<view class="tag">
						{{$t('必填')}}
					</view>
					<view class="btn" @click="openNameModal">
						<u-input :value="formData.title" :placeholder="$t('请输入货物名称')" disabled />
						<u-icon name="arrow-right" color="#8C8C8C" size="28rpx"></u-icon>
					</view>
				</view>

				<view class="package">
					<view class="title">
						{{$t('包装方式')}}
					</view>
					<view class="list_item">
						<view class="item" v-for="(item, index) in packageTypes" :key="index"
							:class="{ 'active': formData.package_id === item.id }" @click="selectPackageType(item.id)">
							{{ item.title }}
						</view>
						<view class="item_input" v-if="formData.package_id === 0">
							<u-input v-model="formData.package_name" placeholder="填写特殊包装方式"
								:customStyle="{ width: '100%', background: '#F6F7FB', height: '60rpx', padding: '0 20rpx' }"
								fontSize="24rpx" shape="circle" border="none">
							</u-input>
						</view>
					</view>
				</view>
				<view class="package">
					<view class="title">
						{{$t('装卸方式')}}<text>（{{$t('自主装卸可不选')}}）</text>
					</view>
					<view class="list_item">
						<view class="item" v-for="item in unloadTypes" :key="item.id"
							:class="{ 'active': formData.unload_id === item.id }" @click="selectUnloadType(item.id)">
							{{ item.title }}
						</view>
					</view>
				</view>
			</view>

			<view class="bor_bgff">
				<view class="goods_weight">
					<view class="title">
						{{$t('货物重量')}}
					</view>

					<div style="height: 50rpx;">
						<Number v-model="formData.goods_weight"
							:unit="$store.state.publishCommonBody.goods_type == GoodsType.DAJIAN ? '吨' : '千克'"></Number>
					</div>
				</view>
				<view class="goods_weight">
					<view class="title">
						{{$t('货物体积')}}
					</view>
					<Number v-model="formData.goods_volume" unit="m³" />
				</view>
				<view class="goods_weight">
					<view class="title">
						{{$t('货物密度')}}
					</view>
					<view class="blue_text">
						{{ getDensity() }}kg/m³
					</view>
				</view>
				<view class="goods_weight">
					<view class="title">
						{{$t('包装总件数')}}
					</view>
					<Number v-model="formData.goods_num" :zhegnshu="true"></Number>
				</view>
				<view class="goods_chicun">
					<view class="title">
						<view class="name">
							{{$t('特殊尺寸')}}
						</view>
						<view class="btn_add" @click="addSizeGroup">
							<u-icon name="plus" color="#8C8C8C" size="26rpx"></u-icon>
							<text>{{$t('添加')}}</text>
						</view>
					</view>

					<view class="item_cc" v-for="(group, index) in sizeGroups" :key="index">
						<view class="item">
							<u-input v-model="group.length" type="number" :placeholder="$t('长')" fontSize="24rpx"
								shape="circle" border="none"
								:customStyle="{ width: '100%', background: '#F6F7FB', height: '70rpx', padding: '0 20rpx' }">
								<template v-slot:suffix>
									<view class="unit">
										{{$t('米')}}
									</view>
								</template>
							</u-input>
						</view>
						<view class="item">
							<u-input v-model="group.width" type="number" placeholder="宽" fontSize="24rpx" shape="circle"
								border="none"
								:customStyle="{ width: '100%', background: '#F6F7FB', height: '70rpx', padding: '0 20rpx' }">
								<template v-slot:suffix>
									<view class="unit">
										{{$t('米')}}
									</view>
								</template>
							</u-input>
						</view>
						<view class="item">
							<u-input v-model="group.height" type="number" placeholder="高" fontSize="24rpx"
								shape="circle" border="none"
								:customStyle="{ width: '100%', background: '#F6F7FB', height: '70rpx', padding: '0 20rpx' }">
								<template v-slot:suffix>
									<view class="unit">
										{{$t('米')}}
									</view>
								</template>
							</u-input>
						</view>

						<view class="item_add" @click="removeSizeGroup(index)">
							<u-icon name="minus-circle" color="#bbb" size="40rpx"></u-icon>
						</view>

					</view>




				</view>

				<view class="goods_photo">
					<view class="title between">
						<div class="fz28">
							{{$t('货物照片')}} <text class="text-gray-900 fz22">(最多9张)</text>
						</div>
						<view class="fz22 text-gray-900">
							{{ fileList1.length }}/9
						</view>
					</view>
					<u-upload :fileList="fileList1" name="1" multiple :maxCount="9" :previewFullImage="true"
						@afterRead="afterRead" @delete="deletePic" width="150" height="150">
					</u-upload>

				</view>
			</view>
		</div>



		<div class="p-30 bg-white" style="border-top: 1px solid #ddd;">
			<div class="submit center h-100 bg-primary text-white fz32 rounded-50" @click="submit">
				{{$t('确认')}}
			</div>
		</div>

		<!-- 添加测试按钮 -->
		<view class="test-btn" @click="fillTestData">
			{{$t('填充测试数据')}}
		</view>

	</view>
</template>


<style lang="scss">
.header {
	font-size: 34rpx;
	height: 100rpx;
	line-height: 100rpx;
	font-weight: bold;
	text-align: center;
	position: relative;
	padding-top: var(--status-bar-height);
	background: #fff;
}

.back {
	position: absolute;
	width: 70rpx;
	height: 70rpx;
	top: 18rpx;
}


.footer_none {
	height: 200rpx;
}

.goods_photo {
	padding: 40rpx 24rpx 20rpx;

	.title {
		font-size: 28rpx;
		line-height: 40rpx;
		font-weight: 600;
		padding-bottom: 20rpx;
	}

}

.goods_chicun {
	padding: 40rpx 24rpx 0;

	.item_cc {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-top: 20rpx;

		.item {
			margin-right: 30rpx;
		}

		.unit {
			color: #1D1D1D;
			font-size: 26rpx;
			line-height: 34rpx;
		}
	}

	.title {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.name {
			font-size: 28rpx;
			line-height: 40rpx;
			font-weight: 600;

		}

		.btn_add {
			flex-shrink: 0;
			display: flex;
			align-items: center;

			text {
				display: block;
				color: #8C8C8C;
				font-size: 26rpx;
				line-height: 28rpx;
				padding-left: 4rpx;
			}
		}
	}
}

.goods_weight {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 40rpx 24rpx 0;

	.title {
		color: #1D1D1D;
		font-size: 28rpx;
		font-weight: 600;
		line-height: 28rpx;
		margin-right: auto;
	}

	.unit {
		flex-shrink: 0;
		width: 60rpx;
		font-size: 26rpx;
		text-align: right;
	}

	.blue_text {
		color: #278AFF;
		font-size: 28rpx;
		font-weight: 600;
		line-height: 28rpx;
	}
}

.package {
	padding: 0 24rpx;

	.title {
		font-size: 28rpx;
		line-height: 40rpx;
		font-weight: 600;

		text {
			color: #8C8C8C;
		}
	}

	.list_item {
		display: flex;
		align-items: flex-start;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-content: flex-start;
		gap: 14rpx;
		padding: 20rpx 0 30rpx;

		.item_input {
			width: 440rpx;
			font-size: 24rpx;
		}

		.item {
			width: 150rpx;
			height: 64rpx;
			flex-shrink: 0;
			border-radius: 50px;
			background: #F6F7FB;
			color: #1D1D1D;
			font-size: 24rpx;
			line-height: 64rpx;
			text-align: center;
			border: 1px solid transparent;
		}
	}
}

.goods_info_title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 96rpx;
	padding: 0 16rpx 0 24rpx;

	.name {
		font-size: 28rpx;
		line-height: 40rpx;
		font-weight: 600;
	}

	.btn {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: auto;
		font-size: 28rpx;
		line-height: 40rpx;
		font-weight: 600;
	}

	.tag {
		flex-shrink: 0;
		width: 64rpx;
		height: 32rpx;
		border-radius: 500rpx;
		background: #D7E8FA;
		color: #278AFF;
		font-size: 18rpx;
		line-height: 32rpx;
		text-align: center;
		margin-left: 10rpx;
	}
}

.bor_bgff {
	margin: 20rpx 30rpx;
	background: #fff;
	border-radius: 20rpx;
}

.guanl_order {
	margin: 20rpx 30rpx;
	height: 96rpx;
	background: #fff;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 16rpx 0 24rpx;

	.name {
		font-size: 28rpx;
		line-height: 40rpx;
		font-weight: 600;
	}

	.info {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 600;

	}
}

.tabs_nav {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 86rpx;
	background: #fff;

	.item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;

		&:last-child {
			border-left: 1px solid #eee;
		}

		.name {
			color: #333;
			font-size: 28rpx;
			line-height: 32rpx;
			padding-left: 6rpx;
		}

		&.hover {
			.name {
				color: #278AFF;
			}
		}
	}
}

page {
	background-color: #F6F7FB;
}

.item {
	&.active {
		background: #D7E9FF !important;
		color: #278AFF !important;
		border: 1px solid #278AFF !important;
	}
}

/* {{$t('货物名称')}}弹窗样式 */
.name-modal {
	padding: 30rpx 0;
	min-height: 400rpx;

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;

		.history-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 600;
		}

		.clear-btn {
			font-size: 24rpx;
			color: #999;
			padding: 10rpx;
		}
	}

	.history-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 20rpx;
		gap: 20rpx;

		.history-item {
			padding: 10rpx 30rpx;
			background: #F6F7FB;
			border-radius: 30rpx;
			font-size: 24rpx;
			color: #666;
			border: 1px solid transparent;

			&:active {
				background: #D7E9FF;
				color: #278AFF;
				border-color: #278AFF;
			}
		}
	}
}

/* 测试{{$t('按钮')}}样式 */
.test-btn {
	position: fixed;
	right: 300rpx;
	top: 20rpx;
	background: #ff9900;
	color: #fff;
	padding: 10rpx 20rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	z-index: 999;
}
</style>
